using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using netcore_comm.JWT;
using netcore_comm.Nlog;
using netcore_comm.Redis;
using netcore_comm.SqlSugar;
using netcore_service.Dto;
using netcore_service.IRepository;
using netcore_service.IService;
using netcore_service.Model;
using Newtonsoft.Json;
using SqlSugar;
using System.Data;
using System.Security.Claims;

namespace netcore_service.Service
{
    /// <summary>
    /// 
    /// </summary>
    [ApiExplorerSettings(GroupName = "v1")]
    public class SchoolService : ISchoolService
    {
        private readonly ISchoolRepository _schoolRepository;
        private readonly ISqlSugarFactory _sqlSugarFactory;
        private readonly RedisHelper _redisHelper;
        private readonly IJWTService _iJWTService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IManagerRepository _managerRepository;
        private readonly INLogHelper _nLogHelper;
        private readonly IChatService _chatService;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="schoolRepository"></param>
        /// <param name="sqlSugarFactory"></param>
        public SchoolService(ISchoolRepository schoolRepository, ISqlSugarFactory sqlSugarFactory
            , RedisHelper redisHelper
            , IJWTService iJWTService
            , IHttpContextAccessor httpContextAccessor
            , IWebHostEnvironment hostingEnvironment
            , IManagerRepository managerRepository,
            INLogHelper nLogHelper,
            IChatService chatService
            )
        {
            _sqlSugarFactory = sqlSugarFactory;
            _schoolRepository = schoolRepository;
            _redisHelper = redisHelper;
            _iJWTService = iJWTService;
            _httpContextAccessor = httpContextAccessor;
            _hostingEnvironment = hostingEnvironment;
            _managerRepository = managerRepository;
            _nLogHelper = nLogHelper;
            _chatService = chatService;
        }

        /// <summary>
        /// 添加及修改
        /// </summary>
        /// <param name="schoolInfo"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        [Authorize]
        public async Task<ApiResult<string>> SchoolInfoAddOrUpdate(SchoolInfo schoolInfo)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);
            if (schoolInfo != null)
            {
                if (schoolInfo.type == "90001")
                {
                    schoolInfo.state = "1";
                }
                if (!string.IsNullOrEmpty(schoolInfo.Id))
                {
                    await _redisHelper.KeyDeleteAsync(schoolInfo.Id);
                }
                await _redisHelper.KeyDeleteAsync("school_list_" + schoolInfo.type);
                if (string.IsNullOrEmpty(schoolInfo.Id))
                {
                    //添加
                    schoolInfo.Id = Guid.NewGuid().ToString();
                    schoolInfo.ModifyUser = "admin";
                    await _schoolRepository.InsertAsync(db, schoolInfo);
                }
                else
                {
                    //修改
                    await _schoolRepository.UpdateAsync(db, schoolInfo);
                }
                await deleteKey(schoolInfo.Id);
            }
            else
            {
                return APIResult.GetError("实体为空！");
            }
            return APIResult.GetSuccess("操作成功");
        }

        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<ApiResult<string>> SchoolInfoDel(string Id)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);
            if (Id != null)
            {
                await deleteKey(Id);
                await _redisHelper.KeyDeleteAsync(Id);
                await _redisHelper.KeyDeleteAsync("school_list_90001");
                await _redisHelper.KeyDeleteAsync("school_list_90002");
                await _schoolRepository.DeleteAsync(db, new SchoolInfo() { Id = Id });
            }
            return APIResult.GetSuccess("删除成功");
        }

        [Authorize]
        [HttpPost]
        public async Task<ApiResult<dynamic>> SchoolInfoList(SchoolInfoPo po)
        {
            var user = _httpContextAccessor.HttpContext.User;
            //拿到用户角色Role
            if (user.Identity.IsAuthenticated)
            {
                // 获取用户的角色信息
                var roles = user.Claims.Where(c => c.Type == "Role").Select(c => c.Value).FirstOrDefault();
                if (roles != "Manager")
                {
                    var school = await _managerRepository.GetSchoolUserList(user.Identity.Name, po.type);
                    (dynamic data, int total) = await _schoolRepository.SchoolInfoList(po, school);

                    return APIResult.GetSuccess<dynamic>(data, total);
                }
            }
            (dynamic data1, int total1) = await _schoolRepository.SchoolInfoList(po, new List<string>());
            return APIResult.GetSuccess<dynamic>(data1, total1);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<ApiResult<SchoolInfo>> SchoolInfoById(string Id)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData));
            var model = await _schoolRepository.GetModelAsync(db, e => e.Id == Id);
            if (model != null)
            {
                model.imgList = _schoolRepository.GetImgList(model.Id);
            }
            return APIResult.GetSuccess<SchoolInfo>(model);
        }

        /// <summary>
        /// 小程序和第三方用,获取学校列表
        /// </summary>
        /// <param name="po"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<List<SchoolInfoDtoM>>> SchoolList(SchoolInfoPo po)
        {
            var list = await _redisHelper.ListRangeAsync<SchoolInfoDtoM>("school_list_" + po.type);
            if (list == null || list.Count == 0)
            {
                list = await _schoolRepository.SchoolList(po);
                if (list != null && list.Count > 0)
                {
                    await _redisHelper.ListLeftPushAsync<SchoolInfoDtoM>("school_list_" + po.type, list);
                }
            }
            if (!string.IsNullOrEmpty(po.Name))
            {
                list = list?.Where(e => e.Name.Contains(po.Name)).ToList();
            }
            if (!string.IsNullOrEmpty(po.ksxs))
            {
                list = list?.Where(e => e.Schoolksxs == po.ksxs).ToList();
            }
            if (!string.IsNullOrEmpty(po.schoolYxcc))
            {
                list = list?.Where(e => e.SchoolYxcc == po.schoolYxcc).ToList();
            }
            if (!string.IsNullOrEmpty(po.CityParam))
            {
                list = list?.Where(e => po.CityParam.Contains(e.City)).OrderBy(e => e.Sort).ThenBy(e => e.SchoolCode).ToList();
            }
            else
            {
                list = list.OrderBy(e => e.Sort).ThenBy(e => e.SchoolCode).ToList();
            }
            return APIResult.GetSuccess<List<SchoolInfoDtoM>>(list);
        }

        [HttpGet]
        public async Task<ApiResult<SchoolInfoDto>> SchoolById(string Id, string uid)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData));
            var model = await _redisHelper.StringGetAsync<SchoolInfoDto>(Id);
            if (model == null)
            {
                model = await _schoolRepository.SchoolById(Id);
                if (model != null)
                {
                    await _redisHelper.StringSetAsync<SchoolInfoDto>(Id, model);
                }
            }
            //if (model.state != "1")
            //{
            //    return APIResult.GetError<SchoolInfoDto>("院校信息审核中");
            //}
            model.scDate = DateTime.Now;
            model.uid = uid;
            CollectionPo coll = new()
            {
                schoolId = model.Id,
                schoolName = model.Name,
                openid = model.uid,
                codate = DateTime.Now
            };
            await _redisHelper.ListLeftPushAsync("school_count_" + model.type, coll);
            return APIResult.GetSuccess<SchoolInfoDto>(model);
        }
        /// <summary>
        /// 根据id和类型获取详情
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<SchoolDetailDto>> SchoolDetail(string Id, string type)
        {
            SchoolDetailDto model = await _redisHelper.StringGetAsync<SchoolDetailDto>(Id + type);
            if (model == null)
            {
                model = await _schoolRepository.SchoolDetail(Id, type);

                if (model != null)
                {
                    await _redisHelper.StringSetAsync<SchoolDetailDto>(Id + type, model);
                }
            }
            return APIResult.GetSuccess(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<ApiResult<dynamic>> GetSchoolCount(string type, string date)
        {
            var list = await _redisHelper.ListRangeAsync<CollectionPo>($"school_count_{type}");
            var group = list.WhereIF(!string.IsNullOrEmpty(date), e => e.codate > Convert.ToDateTime(date.Split(',')[0]) & e.codate < Convert.ToDateTime(date.Split(',')[1]).AddDays(1)).
                GroupBy(e => new { e.schoolName, e.schoolId }).Select(g => new
                {
                    SchoolName = g.Key.schoolName,
                    NullCount = g.Count(s => s.openid == null),
                    NotNullCount = g.Count(s => s.openid != null),
                    CollectionCount = _schoolRepository.getCollectionbySchool(g.Key.schoolId)
                }).ToList();
            return APIResult.GetSuccess<dynamic>(group);
        }


        /// <summary>
        /// 生成学校Key
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<ApiResult<int>> GenerateSchoolKey(string type)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);
            var list = await db.Queryable<SchoolInfoKey>().ToListAsync();
            foreach (var item in list)
            {
                item.Key = MD5Encrypt.Encrypt(item.Name + DateTime.Now.Year);
            }
            int i = await db.Updateable(list).UpdateColumns(e => new { e.Key }).ExecuteCommandAsync();
            var schoolList = await db.Queryable<SchoolInfo>().Where(e => e.type == type).ToListAsync();
            schoolList.ForEach(e =>
            {
                var key = list.FirstOrDefault(a => a.Name == e.Name);
                if (key != null)
                {
                    e.schoolKey = key.Key;
                }
            });
            await db.Updateable<SchoolInfo>(schoolList).UpdateColumns(e => new { e.schoolKey }).ExecuteCommandAsync();
            return APIResult.GetSuccess<int>(i);
        }

        /// <summary>
        /// 验证Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        //[Authorize]
        public async Task<ApiResult<SchoolInfo>> VerifySchoolKey(string key, string type)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData));
            var list = await db.Queryable<SchoolInfoKey>().Where(e => e.Key == key).FirstAsync();
            if (list != null)
            {

                SchoolInfo model = await _schoolRepository.GetModelAsync(db, e => e.Name == list.Name && e.type == type);

                if (model == null)
                {
                    model = new SchoolInfo();
                    model.Name = list.Name;
                    model.schoolKey = list.Key;
                    return APIResult.GetSuccess<SchoolInfo>(model);
                }
                else
                {
                    model.imgList = await db.Queryable<School_Image>().Where(e => e.SchoolId == model.Id).ToListAsync();

                    return APIResult.GetSuccess<SchoolInfo>(model);
                }
            }
            else
            {
                return APIResult.GetError<SchoolInfo>("无效的key");
            }
        }
        /// <summary>
        /// 添加及修改
        /// </summary>
        /// <param name="schoolInfo"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        //[Authorize]
        public async Task<ApiResult<string>> SchoolInfoUpdate(SchoolInfo schoolInfo)
        {
            var db = _sqlSugarFactory.GetInstance(nameof(netData));
            var list = await db.Queryable<SchoolInfoKey>().Where(e => e.Key == schoolInfo.schoolKey).FirstAsync();

            if (list == null)
            {
                return APIResult.GetError<string>("请使用正确的密钥");
            }
            var dbw = _sqlSugarFactory.GetInstance(nameof(netData), DBOperateType.Write);
            try
            {

                if (schoolInfo != null)
                {
                    if (!string.IsNullOrEmpty(schoolInfo.Id))
                    {
                        await _redisHelper.KeyDeleteAsync(schoolInfo.Id);
                    }
                    await _redisHelper.KeyDeleteAsync("school_list_" + schoolInfo.type);
                    if (string.IsNullOrEmpty(schoolInfo.Id))
                    {
                        //添加
                        schoolInfo.Id = Guid.NewGuid().ToString();
                        schoolInfo.ModifyUser = "admin";
                        schoolInfo.ModifyDate = DateTime.Now;
                        await _schoolRepository.InsertAsync(dbw, schoolInfo);
                    }
                    else
                    {
                        schoolInfo.ModifyDate = DateTime.Now;
                        //修改
                        await _schoolRepository.UpdateAsync(dbw, schoolInfo);
                    }
                    //保存图片
                    await _schoolRepository.saveImage(schoolInfo);
                    await deleteKey(schoolInfo.Id);
                }
                else
                {
                    return APIResult.GetError("实体为空！");
                }

            }
            catch (Exception ex)
            {
                _nLogHelper.Info($"SchoolInfoUpdate:" + schoolInfo);
                _nLogHelper.Error($"SchoolInfoUpdate:" + ex.ToString());
                throw;
            }
            return APIResult.GetSuccess(schoolInfo.Id);
        }

        /// <summary>
        /// 上传PDF文件
        /// </summary>
        /// /// <param name="pdffile"></param>
        /// <returns></returns>
        [HttpPost("uploadPdf")]
        public async Task<ApiResult<string>> uploadPdf(IFormFile file)
        {
            string key = _httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString();

            var db = _sqlSugarFactory.GetInstance(nameof(netData));
            var list = await db.Queryable<SchoolInfoKey>().Where(e => e.Key == key).FirstAsync();

            if (list == null)
            {
                return APIResult.GetError<string>("请使用正确的密钥");
            }
            if (file == null || file.Length == 0)
            {
                return APIResult.GetError<string>("File is not selected or is empty");
            }
            // 验证文件类型
            if (file.ContentType != "application/pdf")
            {
                return APIResult.GetError<string>("Only PDF files are allowed");
            }
            // 生成唯一的文件名
            string uniqueFileName = Guid.NewGuid().ToString().Substring(0, 4) + "_" + file.FileName;

            // 指定文件保存路径
            string filePath = Path.Combine(_hostingEnvironment.WebRootPath + "/Logo");
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = Path.Combine(filePath, uniqueFileName);
            try
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                string nginx = "wechatappletapi";
                // 在这里可以对文件流进行进一步处理，比如保存到数据库、进行文件转换等操作
                var baseUrl = $"https://{_httpContextAccessor.HttpContext?.Request.Host}/{nginx}/Logo/";
                var fileUrl = baseUrl + uniqueFileName;

                // 处理完成后返回成功信息
                return APIResult.GetSuccess<string>(fileUrl);
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return APIResult.GetError<string>($"An error occurred while uploading the file: {ex.Message}");
            }
        }

        [HttpPost("upload")]
        public async Task<ApiResult<string>> UploadImg(IFormFile file)
        {
            string key = _httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString();

            var db = _sqlSugarFactory.GetInstance(nameof(netData));
            var list = await db.Queryable<SchoolInfoKey>().Where(e => e.Key == key).FirstAsync();

            if (list == null)
            {
                return APIResult.GetError<string>("请使用正确的密钥");
            }
            if (file == null || file.Length == 0)
            {
                return APIResult.GetError<string>("File is not selected or is empty");
            }
            // 验证文件类型
            if (file.ContentType != "image/jpeg" && file.ContentType != "image/png")
            {
                return APIResult.GetError<string>("Only JPG and PNG files are allowed");
            }
            // 生成唯一的文件名
            string uniqueFileName = Guid.NewGuid().ToString().Substring(0, 4) + "_" + file.FileName;

            // 指定文件保存路径
            string filePath = Path.Combine(_hostingEnvironment.WebRootPath + "/Logo");
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = Path.Combine(filePath, uniqueFileName);
            try
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                string nginx = "wechatappletapi";
                // 在这里可以对文件流进行进一步处理，比如保存到数据库、进行文件转换等操作
                var baseUrl = $"https://{_httpContextAccessor.HttpContext?.Request.Host}/{nginx}/Logo/";
                var fileUrl = baseUrl + uniqueFileName;

                // 处理完成后返回成功信息
                return APIResult.GetSuccess<string>(fileUrl);
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return APIResult.GetError<string>($"An error occurred while uploading the file: {ex.Message}");
            }
        }


        private async Task deleteKey(string Id)
        {
            try
            {
                await _redisHelper.KeyDeleteAsync(Id + "zszc");
                await _redisHelper.KeyDeleteAsync(Id + "zyjh");
                await _redisHelper.KeyDeleteAsync(Id + "zxzx");
                await _redisHelper.KeyDeleteAsync(Id + "zyjs");
                await _redisHelper.KeyDeleteAsync(Id + "lnfs");
                await _redisHelper.KeyDeleteAsync(Id + "xxjj");
            }
            catch
            {

            }

        }

        [HttpGet]
        public async Task<ApiResult<dynamic>> GetSchoolCountTop(string type)
        {
            var list = await _redisHelper.ListRangeAsync<CollectionPo>("school_count_" + type);
            var group = list.GroupBy(e => new { e.schoolName, e.schoolId }).Select(e => new { id = e.Key.schoolId, name = e.Key.schoolName, Count = e.Count() }).OrderByDescending(e => e.Count).Take(10).ToList();
            return APIResult.GetSuccess<dynamic>(group);

        }

        /// <summary>
        /// 最近浏览
        /// </summary>
        /// <param name="type"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<SchoolInfoDto>>> GetSchoolCountByOpenid(string type, string uid)
        {
            if (string.IsNullOrEmpty(uid))
            {
                return APIResult.GetError<List<SchoolInfoDto>>("请在登录后查看最近浏览");
            }
            var list = await _redisHelper.ListRangeAsync<CollectionPo>("school_count_" + type);
            var group = list.Where(e => e.openid == uid).OrderByDescending(e => e.codate).Take(30).ToList();
            var Ids = group.Select(e => e.schoolId).ToList();
            List<SchoolInfoDto> schoollist = await _schoolRepository.SchoolListByIds(Ids);
            return APIResult.GetSuccess<List<SchoolInfoDto>>(schoollist);

        }
        /// <summary>
        /// 加入收藏
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddCollection(Collection data)
        {
            var openidlist = await _redisHelper.ListRangeAsync<string>("getOpenId");
            if (!openidlist.Where(e => e == data.openid).Any())
            {
                return APIResult.GetError(0);
            }
            var i = await _schoolRepository.AddCollection(data);
            if (i > 0)
            {
                return APIResult.GetSuccess(i);
            }
            else
            {
                return APIResult.GetError(i);
            }
        }

        //取消收藏
        [HttpPost]
        public async Task<ApiResult<int>> cancelCollect(string Id, string Uid)
        {
            var i = await _schoolRepository.cancelCollect(Id, Uid);
            if (i > 0)
            {
                return APIResult.GetSuccess(i);
            }
            else
            {
                return APIResult.GetError(i);
            }
        }

        [HttpGet]
        public async Task<ApiResult<List<SchoolInfoDto>>> getMyCollection(string uid)
        {
            var list = await _schoolRepository.getCollection(uid);
            return APIResult.GetSuccess<List<SchoolInfoDto>>(list);
        }

        [HttpGet]
        public async Task<ApiResult<bool>> getCollectionbyId(string schoolId, string uid)
        {
            var list = await _schoolRepository.getCollectionbyId(schoolId, uid);
            return APIResult.GetSuccess(list);
        }

        [HttpGet]
        public async Task<ApiResult<SchoolInfo>> getSchoolIdByOpenid(string openId)
        {
            var list = await _schoolRepository.getSchoolIdByOpenid(openId);
            return APIResult.GetSuccess(list);
        }
        

    }
}
